import { defineStore } from "pinia";
//登录成功:获取到用户唯一标识token,利用函数持久化存储|获取|删除token操作
import { reqUserRegister, reqUserLogin,reqUserInfo,reqLogout } from '../../api/user/index'
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from '../../utils/token-utils';

export const useUserInfoStore = defineStore('userInfo', {
    state: (): any => ({
        token: '', //存储token 
        name: '',//存储用户名字
        avatar: '',//存储用户头像
        menuRoutes: [],//路由数组
        lose:'123'

    }),
    actions: {
        //点击登录按钮:调用仓库login方法,携带账号与密码
        async login(phone: number, password: any) {
            //发登录请求:如果登录成功返回token
            let result: any = await reqUserLogin({ phone, password });
            if (result.code == 200) {
                
                //本地持久化存储token 
                SET_TOKEN(result.data.token); // 存到localStorage;
                this.token = result.data.token
                this.name = result.data.nickName
            }else{
                alert(result.message)
                return Promise.reject(new Error(result.message))
            }
        },
        //注册账号的请求发送
        async register(data:any) {
            let result = await reqUserRegister(data);
            if(  result.code==200){
                return result;
            }else{
                alert(result.message);
                return Promise.reject(new Error(result.message))
            }
           
        },
        //获取用户信息
        async uerxinxi(){
            let result = await  reqUserInfo();
            console.log(result)
            if(result.code == 200){
                    this.name= result.data.nickName
                    this.avatar= result.data.headImg
                 }
            
        },
        //退出登录
        async userLogout(){
            let result = await reqLogout();
            REMOVE_TOKEN();
            if(result.code == 200){
                this.name = '';
                this.token = ''
            }
        }
    },
    getters: {

    }
})